import CryptoJS from 'crypto-js';
import { JSEncrypt } from 'jsencrypt';

// 配置（应从安全渠道获取，如后端API）
const CONFIG = {
  RSA_PUBLIC_KEY: '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMmDsLT3/7YM0ml5DtDZIH0PUD/sdmq+ypQJB2u+UJ7l/0OOxKvJbmVhEpbb4uh1lchAHorMU2v2HbvnDYvn70QKP370kdeOZORhgYmxp/k17v+CNoAxI3v9jHrvAjoKkKujgtwS9u3wpmJGxspzsHuRe+EJ/pZn5rCaydiuPGxQIDAQAB-----END PUBLIC KEY-----',
  HMAC_KEY: '5687d47e8e816480261d8a83eeacb3619cba7e38a3c41fc7a6bed45051f2ec47', //HMAC密钥：一个复杂的字符串 用于生成签名，需与后端一致
  TIMESTAMP_WINDOW: 300000, // 时间戳有效窗口：5分钟（毫秒）
};


const encrypt = {
  /**
   * 生成随机AES密钥（16字节，128位）
   */
  generateAESKey: () => {
    return CryptoJS.lib.WordArray.random(128 / 8).toString(CryptoJS.enc.Base64);
  },

  /**
   * 使用AES-CBC模式加密数据
   * @param {string} data 明文数据
   * @param {string} key Base64编码的AES密钥
   * @returns {Object} { ciphertext: string, iv: string }
   */
  encryptDataWithAES: (data, key) => {
    const iv = CryptoJS.lib.WordArray.random(128 / 8);
    const keyBytes = CryptoJS.enc.Base64.parse(key);
    const encrypted = CryptoJS.AES.encrypt(data, keyBytes, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return {
      ciphertext: encrypted.toString(),
      iv: CryptoJS.enc.Base64.stringify(iv)
    };
  },

  /**
   * 使用RSA公钥加密AES密钥
   * @param {string} aesKey 
   * @returns {string} Base64编码的加密结果
   */
  encryptAESKeyWithRSA: (aesKey) => {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(CONFIG.RSA_PUBLIC_KEY);
    const encrypted = encryptor.encrypt(aesKey);
    if (!encrypted) {
      throw new Error('RSA加密失败');
    }
    return encrypted;
  },

  /**
   * 生成HMAC-SHA256签名
   * @param {string} timestamp 
   * @param {string} nonce 
   * @param {string} encryptedData 
   * @returns {string} 十六进制签名
   */
  generateSignature: (timestamp, nonce, encryptedData) => {
    const hmac = CryptoJS.HmacSHA256(
      `${timestamp}${nonce}${encryptedData}`,
      CONFIG.HMAC_KEY
    );
    return hmac.toString(CryptoJS.enc.Hex);
  },

  /**
   * 构建安全请求载荷
   * @param {Object|string} data 要发送的业务数据
   * @returns {Promise<Object>} 加密后的载荷
   */
  buildSecurePayload:  (data) => {
    // 1. 准备基础组件
    const timestamp = Date.now().toString();
    const nonce = CryptoJS.lib.WordArray.random(16).toString(CryptoJS.enc.Hex); // 生成16字节随机数
    const dataStr = typeof data === 'object' ? JSON.stringify(data) : data;

    // 2. AES加密业务数据
    const aesKey = encrypt.generateAESKey();
    const aesEncryptedResult = encrypt.encryptDataWithAES(dataStr, aesKey);

    // 3. RSA加密AES密钥
    const encryptedAESKey = encrypt.encryptAESKeyWithRSA(aesKey);

    // 4. 生成HMAC签名（签名内容包含时间戳、Nonce和加密数据）
    const signature = encrypt.generateSignature(timestamp, nonce, aesEncryptedResult.ciphertext);

    // 5. 组装最终请求载荷
    return {
      encryptedData: aesEncryptedResult.ciphertext, // AES加密后的业务数据
      encryptedKey: encryptedAESKey, // RSA加密后的AES密钥
      iv: aesEncryptedResult.iv, // AES加密的IV
      timestamp: timestamp, // 时间戳
      nonce: nonce, // 随机数
      signature: signature // HMAC签名
    };
  }
};

export default encrypt;